import { RootState, RootThunkAction } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'

// 获取用户信息
function useInitState<T extends keyof RootState>(action: RootThunkAction, reducerName: T) {
  const dispatch = useDispatch()
  // RootState 人为的设置state的类型,让ts的类型生效
  const state = useSelector((state: RootState) => {
    // 让类型校验可以正常生效
    return state[reducerName]
  })

  useEffect(() => {
    dispatch(action)
  }, [dispatch])

  return state
}

export { useInitState }
